<script lang='ts' setup>
import { computed } from "vue";
import EditContainer from '../container/fat-form-create-drag-container-editor.vue'
import ViewContainer from '../container/fat-form-ceate-container-view.vue'
import { IFormItem } from '../type'
import { Plus, Delete } from "@element-plus/icons-vue";

interface IEmit {
  (event: 'update:modelValue', data: any): void
}
const props = defineProps<{
  item: IFormItem;
  modelValue: any;
  mode?: "edit" | "view"
}>()
const emit = defineEmits<IEmit>()
const refreshLayout = inject<Function>("refreshLayout")
const modelValue = computed({
  get() {
    return props.modelValue
  }, set(val) {
    emit('update:modelValue', val)
  }
})

onMounted(() => {
  if (!modelValue.value) {
    modelValue.value = []
  }
})
function addRow() {
  const obj = getParams(props.item.children)
  modelValue.value.push(obj)
  refreshLayout && refreshLayout()
}
function removeRow() {
  if (modelValue.value.length === props.item.rowLength) return
  modelValue.value.pop()
  refreshLayout && refreshLayout()
}
function getParams(items: IFormItem[]) {
  const params = {}
  items.forEach((i) => {
    if (i.type !== "arrayContainer") {
      //@ts-ignore
      params[i.key] = null
    } else {
      //@ts-ignore
      params[i.key] = [getParams(i.children)]
    }
  })
  return params
}
</script>

<template>
  <EditContainer v-if="mode === 'edit'" item-key="id" :list="item.children" />
  <div class="array-container" v-else style="width:100%">
    <ViewContainer :form-params="modelValue[item.rowIndex!]" item-key="id" :layout-list="item.children"
      :is-container="true" @add-row="addRow" />
    <el-button-group v-if="item.rowIndex === modelValue.length - 1" class="temp-input">
      <el-button class="btn" type="success" @click="addRow" :icon="Plus" text circle></el-button>
      <el-button class="btn" type="danger" @click="removeRow" :icon="Delete" text circle
        :disabled="modelValue.length <= item.rowLength"></el-button>
    </el-button-group>
  </div>
</template>

<style lang='scss' scoped>
.array-container {
  width: 100%;
  display: flex;

  .temp-input {
    align-self: flex-end;
    width: 68px;
  }

  :deep() {}
}
</style>